package demos;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

class Resource implements Runnable {
	private static Random rand = new Random();
	private Semaphore sem;
	
	public Resource(Semaphore sem) {
		this.sem = sem;
	}
	@Override
	public void run() {
		try {
			System.out.println(Thread.currentThread().getName() + "申请资源");
			TimeUnit.MILLISECONDS.sleep(rand.nextInt(2000));
			sem.acquire();
			System.out.println("剩余资源：" + sem.availablePermits() + " " + Thread.currentThread().getName() + "获得资源");
			TimeUnit.MILLISECONDS.sleep(rand.nextInt(2000));
			sem.release();			
		} catch (InterruptedException e) {
			
		}
	}
}
public class SemaphoreTest {
	public static void main(String[] args) {
		Semaphore sem = new Semaphore(4);
		ExecutorService exec = Executors.newCachedThreadPool();
		for(int i = 0; i < 20; i++)
			exec.execute(new Resource(sem));
		exec.shutdown();
	}
}
